//
//  SegmentViewController.m
//  XinYiGou
//
//  Created by Angel_Yan on 2017/8/8.
//  Copyright © 2017年 Angel_Yan. All rights reserved.
//

#import "SegmentViewController.h"


@implementation SegmentItemModel

- (instancetype)init
{
	self = [super init];
	if (self) {
		_mArrData = [[NSMutableArray alloc] init];
		_pageIndex = 1;
	}
	return self;
}

@end



@interface SegmentViewController () <UICollectionViewDelegate , UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
	BOOL _isClickTitle;
    CGFloat _titleHight;
}

@end

@implementation SegmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


- (void)setupData {
    [super setupData];
    self.selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.mArrData = [[NSMutableArray alloc] init];
}


- (void)setup {
    [super setup];
    CGFloat widht = self.colTitleCellWidth == 0 ? 100 :self.colTitleCellWidth;
	// 标题
	{
        _titleHight = 46;
		UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
		layout.itemSize = CGSizeMake(widht, _titleHight);
		layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
		layout.minimumLineSpacing = 0;
		layout.minimumInteritemSpacing = 0;
		
        self.col_Titles = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
		self.col_Titles.backgroundColor = [UIColor whiteColor];
		self.col_Titles.delegate = self;
		self.col_Titles.dataSource = self;
		self.col_Titles.showsVerticalScrollIndicator = NO;
		self.col_Titles.showsHorizontalScrollIndicator = NO;
        [self.col_Titles registerClass:[CollectionViewCellTitles class] forCellWithReuseIdentifier:colCellTitle];
		[self.view addSubview:self.col_Titles];

        // 标题约束
        [self.col_Titles mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.top.equalTo(self.view).offset(SafeAreaTopHeight);
            make.height.equalTo(@(_titleHight));
        }];
        
        // 线条
        //self.viewLineBg = [CommonMethods addLineLabelWithFrame:CGRectZero color:[UIColor lightGrayColor] alpha:0.5];
        [self.view addSubview:self.viewLineBg];
        
        // 线条约束
        [self.viewLineBg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.col_Titles);
            make.right.equalTo(self.col_Titles);
            make.top.equalTo(self.col_Titles.mas_bottom);
            make.height.equalTo(@0.5);
        }];

        
		// 游标
        self.viewLine = [[UIView alloc] initWithFrame:CGRectZero];
		self.viewLine.backgroundColor = KUIColorARGBString(@"1a7ffe");
		self.viewLine.layer.cornerRadius = self.viewLine.height/2;
		[self.col_Titles addSubview:self.viewLine];
        
        // 游标约束
        [self.viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(self.colTitleCellWidth*0.8));
            make.height.equalTo(@(3));
            make.left.equalTo(@(self.colTitleCellWidth*self.selectIndexPath.row+self.colTitleCellWidth*0.1));
            make.top.equalTo(self.col_Titles).offset(_titleHight-3);
        }];
	}
	
	//内容
	{
		CGFloat hight = SCREEN_HEIGHT-self.col_Titles.maxY-SafeAreaBottomHeight;
		UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.estimatedItemSize = CGSizeMake(SCREEN_WIDTH, hight);
		layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
		layout.minimumLineSpacing = 0;
		layout.minimumInteritemSpacing = 0;
        
        self.col_Contents = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
		self.col_Contents.backgroundColor = [UIColor clearColor];
		self.col_Contents.delegate = self;
		self.col_Contents.dataSource = self;
		self.col_Contents.showsVerticalScrollIndicator = NO;
		self.col_Contents.showsHorizontalScrollIndicator = NO;
		self.col_Contents.pagingEnabled = YES;
        [self.view addSubview:self.col_Contents];
        
        // 内容约束
        [self.col_Contents mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.col_Titles);
            make.right.equalTo(self.col_Titles);
            make.top.equalTo(self.viewLineBg.mas_bottom);
            make.bottom.equalTo(self.view);
        }];
	}
    
    AdjustsScrollViewInsetNever(self,self.col_Titles);
}


- (void)setColTitleCellWidth:(CGFloat)colTitleCellWidth {
    _colTitleCellWidth = colTitleCellWidth;
    [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(_colTitleCellWidth*self.selectIndexPath.row+_colTitleCellWidth*0.1));
        make.width.equalTo(@(_colTitleCellWidth*0.8));
    }];
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    // 总宽度
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {

    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {

        CGFloat  contentWidth = size.width;
        CGFloat  contentHeight = (size.height-_titleHight-1);
        [self setupTitleLayout:contentWidth];
        [self setupContentLayout:contentWidth height:contentHeight];
    }];
}


/**
 *  调整布局
 *
 *  @param totalWidth 总宽度
 *  @param orientation 显示的方向
 */

- (void)setupTitleLayout:(CGFloat)totalWidth
{
    if (self.mArrData.count <= 4) {
        self.colTitleCellWidth = totalWidth / self.mArrData.count;
    }

    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.col_Titles.collectionViewLayout ;
    layout.itemSize = CGSizeMake(self.colTitleCellWidth, _titleHight);
    [self.col_Contents.collectionViewLayout invalidateLayout];
    
    if (self.mArrData.count > 0) {
        [self.col_Titles reloadData];
        [self.col_Titles scrollToItemAtIndexPath:self.selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}

- (void)setupContentLayout:(CGFloat)totalWidth height:(CGFloat)totalHeight
{
    
    NSLog(@"%@ col_Contents %@" , NSStringFromCGSize([[UIScreen mainScreen] bounds].size) ,NSStringFromCGPoint(self.col_Contents.contentOffset));
    
    // 内容
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.col_Contents.collectionViewLayout ;
    layout.itemSize = CGSizeMake(totalWidth, totalHeight);
    [self.col_Contents.collectionViewLayout  invalidateLayout];
    
    if (self.mArrData.count > 0) {
        // Get the currently visible cell
        CollectionViewCellTitles *currentCell = (CollectionViewCellTitles*)[self.col_Contents cellForItemAtIndexPath:self.selectIndexPath];
        
        // Resize the currently index to the new flow's itemSize
        CGRect frame = currentCell.frame;
        frame.size = layout.itemSize;
        currentCell.frame = frame;
        [currentCell layoutIfNeeded];
        
        [self.col_Contents scrollToItemAtIndexPath:self.selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }
}




#pragma mark -  UICollectionView delegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.col_Titles) {
        return CGSizeMake(self.colTitleCellWidth, _titleHight);
    } else if (collectionView == self.col_Contents) {
        return CGSizeMake(collectionView.width, collectionView.height);
    }
    return CGSizeZero;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
	return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.mArrData.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	SegmentItemModel *find = self.mArrData[indexPath.row];
	if (collectionView == self.col_Titles) {
        return [self titleCellWithCollection:collectionView indexPath:indexPath object:find];
	}
	
	if (collectionView == self.col_Contents) {
        return [self contentCellWithCollection:collectionView indexPath:indexPath object:find];
	}
	return nil;
	
}

-(CollectionViewCellTitles*)titleCellWithCollection:(UICollectionView *)collectionView indexPath:(NSIndexPath *)indexPath object:(SegmentItemModel *)object {

    CollectionViewCellTitles *cell = [collectionView dequeueReusableCellWithReuseIdentifier:colCellTitle forIndexPath:indexPath];
    // 上面标题
    cell.labTitle.text = object.title;
    cell.labTitle.textColor =  KUIColorARGBString(@"333333");
    cell.labTitle.font = FONT_SYS(kSetting.fontSize_13);
    
    if (indexPath.row == self.selectIndexPath.row) {
        cell.labTitle.textColor =  KUIColorARGBString(@"1a7ffe");
        cell.labTitle.font = FONT_SYS(kSetting.fontSize_14);
    }
    return cell;
}

-(CollectionViewCellCotents*)contentCellWithCollection:(UICollectionView *)collectionView indexPath:(NSIndexPath *)indexPath object:(SegmentItemModel *)object {
    
    CollectionViewCellCotents *cell = [collectionView dequeueReusableCellWithReuseIdentifier:colCellContent forIndexPath:indexPath];
    cell.vcTag = self;
    // 刷新 内容cell 界面
    [cell reloadDataWithData:object];
    return cell;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	
	if (collectionView == self.col_Titles) {
		//
		_isClickTitle = YES;
		self.selectIndexPath = indexPath;
		[self.col_Titles reloadData];
		[self.col_Titles scrollToItemAtIndexPath:self.selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
		
		[self.col_Contents scrollToItemAtIndexPath:self.selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
		return;
	}
	
	if (collectionView == self.col_Contents) {
		return;
	}
	
}




#pragma mark - scrollview delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	if (scrollView == self.col_Contents) {
		_isClickTitle = NO;
	}
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	
	if (scrollView == self.col_Contents) {
        [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(self.colTitleCellWidth*(scrollView.contentOffset.x/scrollView.width)+self.colTitleCellWidth*0.1));
        }];
        
		NSInteger index = roundf(scrollView.contentOffset.x/scrollView.width);
		if (_isClickTitle == NO && index != self.selectIndexPath.row) {
			self.selectIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
			[self.col_Titles reloadData];
			[self.col_Titles scrollToItemAtIndexPath:self.selectIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
		}
	}
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



#pragma mark - cell title


@interface CollectionViewCellTitles()

@end

@implementation CollectionViewCellTitles


- (instancetype)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	if (self) {
		[self setupInterface];
	}
	return self;
}



- (void)setupInterface {
//    self.labTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    self.labTitle = [[UILabel alloc] initWithFrame:CGRectZero];
	self.labTitle.font = FONT_SYS(14.0);
	self.labTitle.textAlignment = NSTextAlignmentCenter;
	[self addSubview:self.labTitle];
    
    [self.labTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.labTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
}

@end





#pragma mark - cell content

@interface CollectionViewCellCotents ()<UITableViewDelegate , UITableViewDataSource>

@property (strong , nonatomic) UITableView *tabViewContent;

@end


@implementation CollectionViewCellCotents

- (instancetype)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		[self setupInterface];
	}
	return self;
}


- (void)setupInterface {
	// 内容
	{
//        self.tabViewContent = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height) style:UITableViewStylePlain];
        self.tabViewContent = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
		self.tabViewContent.delegate = self;
        self.tabViewContent.contentInset = UIEdgeInsetsMake(11, 0, 0, 0);
        self.tabViewContent.backgroundColor = [UIColor clearColor];
		self.tabViewContent.dataSource = self;
        self.tabViewContent.separatorStyle = UITableViewCellSeparatorStyleNone;
		[self.tabViewContent setShowsVerticalScrollIndicator:NO];
		[self addSubview:self.tabViewContent];
        
        [self.tabViewContent mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(self);
        }];

        
        kWeakSelf(self)
		self.tabViewContent.tableFooterView = [[UIView alloc] init];
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself.tabViewContent.mj_header endRefreshing];
            weakself.dataModel.pageIndex = 1;
            [weakself requsetDataWithItem:weakself.dataModel tableView:weakself.tableViewContents];
        }];
        header.ignoredScrollViewContentInsetTop = 11;
		weakself.tabViewContent.mj_header = header;
		
		
		self.tabViewContent.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
			[weakself.tabViewContent.mj_footer endRefreshing];
			weakself.dataModel.pageIndex ++;
            [weakself requsetDataWithItem:weakself.dataModel tableView:weakself.tableViewContents];
		}];
	}
	
}


- (void)layoutSubviews {
    [super layoutSubviews];
    [self.tabViewContent mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
}

- (UITableView *)tableViewContents {
    return _tabViewContent;
}


#pragma mark - 子类需要重写的方法

#pragma mark -- UITableView delegate 子类需要重写方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	return nil;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}



- (void)reloadDataWithData:(SegmentItemModel *)dataModel;
{
	self.dataModel = dataModel;
	// 重置无数据状态
	[self.tabViewContent.mj_footer resetNoMoreData];
	
    // 有数据
    if (self.dataModel.mArrData.count !=  0) {
        [self.tabViewContent reloadData];
        return;
    }
    
    // 无数据重新加载 ,子类来写
    [self requsetDataWithItem:dataModel tableView:self.tableViewContents];
}




- (void)requsetDataWithItem:(SegmentItemModel *)item tableView:(UITableView *)tabV {
    
    
}





@end
